package org.jhotdraw.samples.phototemplate;

import java.awt.Cursor;
import java.awt.Dimension;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import java.awt.dnd.DnDConstants;
import java.awt.dnd.DropTarget;
import java.awt.dnd.DropTargetDragEvent;
import java.awt.dnd.DropTargetDropEvent;
import java.awt.dnd.DropTargetEvent;
import java.awt.dnd.DropTargetListener;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import java.beans.PropertyVetoException;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.net.URI;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.BoxLayout;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JInternalFrame;
import javax.swing.JOptionPane;
import javax.swing.SwingUtilities;
import javax.swing.event.InternalFrameAdapter;
import javax.swing.event.InternalFrameEvent;
import org.jhotdraw.draw.AbstractFigure;
import org.jhotdraw.draw.DefaultDrawingEditor;
import org.jhotdraw.draw.DefaultDrawingView;
import org.jhotdraw.draw.Drawing;
import org.jhotdraw.draw.DrawingEditor;
import org.jhotdraw.draw.DrawingView;
import org.jhotdraw.draw.Figure;
import org.jhotdraw.draw.QuadTreeDrawing;
import org.jhotdraw.draw.io.ImageInputFormat;
import org.jhotdraw.draw.io.ImageOutputFormat;
import org.jhotdraw.draw.io.InputFormat;
import org.jhotdraw.draw.io.OutputFormat;
import org.jhotdraw.draw.io.SerializationInputOutputFormat;
import org.jhotdraw.draw.io.TextInputFormat;
import org.jhotdraw.draw.tool.DnDTracker;
import org.jhotdraw.draw.tool.SelectionTool;
import org.jhotdraw.samples.svg.figures.SVGImageFigure;
import org.jhotdraw.samples.svg.figures.SVGTextFigure;
import org.jhotdraw.samples.svg.io.ImageMapOutputFormat;
import org.jhotdraw.samples.svg.io.SVGInputFormat;
import org.jhotdraw.samples.svg.io.SVGOutputFormat;
import org.jhotdraw.samples.svg.io.SVGZInputFormat;
import org.jhotdraw.samples.svg.io.SVGZOutputFormat;

/**
 *
 * @author Eliazar
 */
public class MainForm extends javax.swing.JFrame {    
    private final String applicationName = "ProImagem3D.jar";
    private static final boolean DEVELOPMENT = true;
//    private static final boolean DEVELOPMENT = false;
    /**
     * Creates new form MainForm
     */
    public MainForm() {
        initComponents();
        setExtendedState(JFrame.MAXIMIZED_BOTH);
//      System.out.println(this.getClass().getProtectionDomain().getCodeSource().getLocation().getPath());        
       if(DEVELOPMENT) {           
           String pathApp = this.getClass().getProtectionDomain().getCodeSource().getLocation().getPath();
           if(pathApp.startsWith("/")) {
               pathApp = pathApp.replaceFirst("/", "");
           }
           pathApp = pathApp.replaceAll("%20", " ");
           String confiFile, dirTemp;
           if(pathApp.endsWith("/")) {
               confiFile = pathApp + "org/jhotdraw/samples/phototemplate/configurations.properties";
               dirTemp = pathApp + "org/jhotdraw/samples/phototemplate/images";
           }else {
               confiFile = pathApp + "/org/jhotdraw/samples/phototemplate/configurations.properties";
               dirTemp = pathApp + "/org/jhotdraw/samples/phototemplate/images";
           }           
           Utilities.setConfigurationFile(confiFile);           
           Utilities.directoryTemp = dirTemp;
       }else {
           String pathApp = this.getClass().getProtectionDomain().getCodeSource().getLocation().getPath();
           if(pathApp.startsWith("/")) {
               pathApp = pathApp.replaceFirst("/", "");
           }
           pathApp = pathApp.replaceAll("%20", " ");
           pathApp = pathApp.replace(applicationName, "");
           String confiFile;
           String dirTemp;
           if(pathApp.endsWith("/")) {
               confiFile = pathApp + "configurations.properties";
               dirTemp = pathApp + "temp";
           }else {
               confiFile = pathApp + "/configurations.properties";
               dirTemp = pathApp + "/temp";
           }           
           File fileDir = new File(dirTemp);
           if(!fileDir.exists()) {
               try {
                   fileDir.mkdir();
               } catch (Exception ex) {
                   MessageDialog.showMessageFail(this, "Error durante a criação do diretório temporário de imagens.");
               }
           }
           Utilities.setConfigurationFile(confiFile);          
           Utilities.directoryTemp = dirTemp;
       }           
       Utilities.loadProperties(Utilities.getConfigurationFile());
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        desktopPane = new javax.swing.JDesktopPane();
        frameRecord = new javax.swing.JInternalFrame();
        jSplitPane1 = new javax.swing.JSplitPane();
        panelMiniPhoto = new javax.swing.JPanel();
        jScrollPane2 = new javax.swing.JScrollPane();
        jTextArea1 = new javax.swing.JTextArea();
        panelRecord = new javax.swing.JPanel();
        jScrollPane3 = new javax.swing.JScrollPane();
        viewRecord = new org.jhotdraw.draw.DefaultDrawingView();
        jPanel1 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        txtOS = new javax.swing.JTextField();
        jButton1 = new javax.swing.JButton();
        jLabel2 = new javax.swing.JLabel();
        cmbTemplate = new javax.swing.JComboBox();
        jMenuBar1 = new javax.swing.JMenuBar();
        jMenu1 = new javax.swing.JMenu();
        jMenuItem1 = new javax.swing.JMenuItem();
        jMenuItem2 = new javax.swing.JMenuItem();
        jMenu2 = new javax.swing.JMenu();
        menuConfigWebServices = new javax.swing.JMenuItem();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        frameRecord.setClosable(true);
        frameRecord.setResizable(true);
        frameRecord.setTitle("Gerar Prontuário");
        frameRecord.setVisible(false);

        jSplitPane1.setDividerLocation(100);
        jSplitPane1.setDividerSize(10);

        panelMiniPhoto.setMaximumSize(new java.awt.Dimension(100, 32767));
        panelMiniPhoto.setPreferredSize(new java.awt.Dimension(100, 272));

        jTextArea1.setEditable(false);
        jTextArea1.setColumns(10);
        jTextArea1.setLineWrap(true);
        jTextArea1.setRows(5);
        jTextArea1.setText("Arraste e Solte Arquivos Aqui");
        jTextArea1.setWrapStyleWord(true);
        jScrollPane2.setViewportView(jTextArea1);

        javax.swing.GroupLayout panelMiniPhotoLayout = new javax.swing.GroupLayout(panelMiniPhoto);
        panelMiniPhoto.setLayout(panelMiniPhotoLayout);
        panelMiniPhotoLayout.setHorizontalGroup(
            panelMiniPhotoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 99, Short.MAX_VALUE)
        );
        panelMiniPhotoLayout.setVerticalGroup(
            panelMiniPhotoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 27, Short.MAX_VALUE)
        );

        jSplitPane1.setLeftComponent(panelMiniPhoto);

        panelRecord.setBorder(javax.swing.BorderFactory.createEtchedBorder());

        viewRecord.setEmptyDrawingMessage("");
        jScrollPane3.setViewportView(viewRecord);

        javax.swing.GroupLayout panelRecordLayout = new javax.swing.GroupLayout(panelRecord);
        panelRecord.setLayout(panelRecordLayout);
        panelRecordLayout.setHorizontalGroup(
            panelRecordLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane3, javax.swing.GroupLayout.DEFAULT_SIZE, 586, Short.MAX_VALUE)
        );
        panelRecordLayout.setVerticalGroup(
            panelRecordLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane3, javax.swing.GroupLayout.DEFAULT_SIZE, 23, Short.MAX_VALUE)
        );

        jSplitPane1.setRightComponent(panelRecord);

        jLabel1.setText("Ordem de Serviço:");

        jButton1.setText("Consultar");

        jLabel2.setText("Template:");

        cmbTemplate.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cmbTemplateActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap(114, Short.MAX_VALUE)
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(txtOS, javax.swing.GroupLayout.PREFERRED_SIZE, 139, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jButton1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jLabel2)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(cmbTemplate, javax.swing.GroupLayout.PREFERRED_SIZE, 130, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
                .addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(txtOS, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addComponent(jButton1)
                .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 28, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addComponent(cmbTemplate, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
        );

        javax.swing.GroupLayout frameRecordLayout = new javax.swing.GroupLayout(frameRecord.getContentPane());
        frameRecord.getContentPane().setLayout(frameRecordLayout);
        frameRecordLayout.setHorizontalGroup(
            frameRecordLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jSplitPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 701, Short.MAX_VALUE)
            .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
        );
        frameRecordLayout.setVerticalGroup(
            frameRecordLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, frameRecordLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jSplitPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 29, Short.MAX_VALUE))
        );

        frameRecord.setBounds(40, 40, 717, 33);
        desktopPane.add(frameRecord, javax.swing.JLayeredPane.DEFAULT_LAYER);

        jScrollPane1.setViewportView(desktopPane);

        jMenu1.setText("Novo");

        jMenuItem1.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_T, java.awt.event.InputEvent.CTRL_MASK));
        jMenuItem1.setIcon(new javax.swing.ImageIcon(this.getClass().getResource("/org/jhotdraw/samples/phototemplate/images/create_template.png")));
        jMenuItem1.setText("Template");
        jMenuItem1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItem1ActionPerformed(evt);
            }
        });
        jMenu1.add(jMenuItem1);

        jMenuItem2.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_P, java.awt.event.InputEvent.CTRL_MASK));
        jMenuItem2.setIcon(new javax.swing.ImageIcon(this.getClass().getResource("/org/jhotdraw/samples/phototemplate/images/create_records.png")));
        jMenuItem2.setText("Prontuário");
        jMenuItem2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItem2ActionPerformed(evt);
            }
        });
        jMenu1.add(jMenuItem2);

        jMenuBar1.add(jMenu1);

        jMenu2.setText("Configuração");

        menuConfigWebServices.setText("Parâmetros");
        menuConfigWebServices.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                menuConfigWebServicesActionPerformed(evt);
            }
        });
        jMenu2.add(menuConfigWebServices);

        jMenuBar1.add(jMenu2);

        setJMenuBar(jMenuBar1);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 543, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 329, Short.MAX_VALUE)
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jMenuItem1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem1ActionPerformed
        disposeAllJInternalFrames();
        loadPanelTemplate();        
    }//GEN-LAST:event_jMenuItem1ActionPerformed
    
    private void disposeAllJInternalFrames() {
        if(desktopPane.getAllFrames() != null && desktopPane.getAllFrames().length > 0) {
            for (JInternalFrame jInternalFrame : desktopPane.getAllFrames()) {
                jInternalFrame.dispose();
            }
        }
    }
    private void jMenuItem2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem2ActionPerformed
        setCursor(new Cursor(Cursor.WAIT_CURSOR));
        disposeAllJInternalFrames();
        System.gc();
        JInternalFrame frame = new JInternalFrame("Gerar Prontuário");
        frame.setClosable(true);
        frame.setMaximizable(true);
        frame.setDefaultCloseOperation(JInternalFrame.DISPOSE_ON_CLOSE);
        PanelRecord p = new PanelRecord();
        frame.setContentPane(p);
        frame.setBounds(0, 0, 800, 600);
        desktopPane.add(frame);
        frame.addInternalFrameListener(new InternalFramePanelRecordListener(p));
        frame.setVisible(true);
        setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
    }//GEN-LAST:event_jMenuItem2ActionPerformed

    private void cmbTemplateActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cmbTemplateActionPerformed
        viewRecord.getDrawing().removeAllChildren();
        if (cmbTemplate.getSelectedIndex() > 0) {
            try {
                SVGInputFormat inputFormat = new SVGInputFormat();
                File template = mapTemplates.get(cmbTemplate.getSelectedItem());
                inputFormat.read(template.toURI(), viewRecord.getDrawing());
            } catch (IOException ex) {
                Logger.getLogger(MainForm.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }//GEN-LAST:event_cmbTemplateActionPerformed

    private void menuConfigWebServicesActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_menuConfigWebServicesActionPerformed
        ConfigWebServicesDialog dialog = new ConfigWebServicesDialog(this, true);
        dialog.setLocationRelativeTo(null);
        dialog.setVisible(true);
    }//GEN-LAST:event_menuConfigWebServicesActionPerformed

    private boolean isFilenameValid(String file) {
        File f = new File(file);
        try {
            if (f.exists()) {
                return true;
            } else {
                f.createNewFile();
                f.delete();
                return true;
            }
        } catch (IOException e) {
            return false;
        }
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        try {
            javax.swing.UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(MainForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(MainForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(MainForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(MainForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new MainForm().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JComboBox cmbTemplate;
    private javax.swing.JDesktopPane desktopPane;
    private javax.swing.JInternalFrame frameRecord;
    private javax.swing.JButton jButton1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JMenu jMenu1;
    private javax.swing.JMenu jMenu2;
    private javax.swing.JMenuBar jMenuBar1;
    private javax.swing.JMenuItem jMenuItem1;
    private javax.swing.JMenuItem jMenuItem2;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JScrollPane jScrollPane3;
    private javax.swing.JSplitPane jSplitPane1;
    private javax.swing.JTextArea jTextArea1;
    private javax.swing.JMenuItem menuConfigWebServices;
    private javax.swing.JPanel panelMiniPhoto;
    private javax.swing.JPanel panelRecord;
    private javax.swing.JTextField txtOS;
    private org.jhotdraw.draw.DefaultDrawingView viewRecord;
    // End of variables declaration//GEN-END:variables
    private DrawingEditor editor;
    private Map<String, File> mapTemplates;
    private String templatPath;
    final Dimension sizeA4 = new Dimension(793, 1122);

    private void loadFrameRecord() {
        try {
            editor = new DefaultDrawingEditor();
            viewRecord.setDrawing(createDrawing());
            editor.add(viewRecord);
            SelectionTool selectionTool = new SelectionTool();
            selectionTool.setDragTracker(new DnDTracker());
            //       ButtonFactory.addSelectionToolTo(tb, editor, selectionTool);
            new DropTarget(panelMiniPhoto, new DragDropFileListener());
            panelMiniPhoto.setLayout(new BoxLayout(panelMiniPhoto, BoxLayout.Y_AXIS));
            //panelMiniPhoto.setBorder(BorderFactory.createEmptyBorder(0, 10, 10, 10));
            frameRecord.setMaximum(true);
            frameRecord.setVisible(true);
            loadTemplates();
        } catch (PropertyVetoException ex) {
            Logger.getLogger(MainForm.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    private Drawing createDrawing() {
        Drawing drawing = new QuadTreeDrawing();
        LinkedList<InputFormat> inputFormats = new LinkedList<InputFormat>();
        inputFormats.add(new SVGZInputFormat());
        inputFormats.add(new SVGInputFormat());
        inputFormats.add(new ImageInputFormat(new SVGImageFigure(), "PNG", "Portable Network Graphics (PNG)", "png", "image/png"));
        inputFormats.add(new ImageInputFormat(new SVGImageFigure(), "JPG", "Joint Photographics Experts Group (JPEG)", "jpg", "image/jpg"));
        inputFormats.add(new ImageInputFormat(new SVGImageFigure(), "GIF", "Graphics Interchange Format (GIF)", "gif", "image/gif"));
        inputFormats.add(new TextInputFormat(new SVGTextFigure()));
        inputFormats.add(new SerializationInputOutputFormat());
        drawing.setInputFormats(inputFormats);

        LinkedList<OutputFormat> outputFormats = new LinkedList<OutputFormat>();
        outputFormats.add(new SVGOutputFormat());
        outputFormats.add(new SVGZOutputFormat());
        outputFormats.add(new ImageOutputFormat());
        outputFormats.add(new ImageOutputFormat("JPG", "Joint Photographics Experts Group (JPEG)", "jpg", BufferedImage.TYPE_INT_RGB));
        outputFormats.add(new ImageOutputFormat("BMP", "Windows Bitmap (BMP)", "bmp", BufferedImage.TYPE_BYTE_INDEXED));
        outputFormats.add(new ImageMapOutputFormat());
        outputFormats.add(new SerializationInputOutputFormat());
        drawing.setOutputFormats(outputFormats);

        return drawing;
    }

    private void loadTemplates() {
        mapTemplates = new HashMap<String, File>();
        File templateDir = new File(templatPath);
        //mapTemplates.put("teste", new File("C:\\Users\\Eliazar\\Desktop\\teste.svg"));
        cmbTemplate.addItem("- selecione -");
        for (File file : templateDir.listFiles()) {
            if (file.isFile() && file.getName().endsWith(".svg")) {
                cmbTemplate.addItem(file.getName().replace(".svg", ""));
                mapTemplates.put(file.getName().replace(".svg", ""), file);
            }
        }
        cmbTemplate.setSelectedIndex(0);
    }

    private void loadPanelTemplate() {
        SizeDialog sizeDialog = new SizeDialog(null, true);
        sizeDialog.setLocationByPlatform(true);
        sizeDialog.setVisible(true);
        if (sizeDialog.getSize() != null) {
            setCursor(new Cursor(Cursor.WAIT_CURSOR));
            JInternalFrame frame = new JInternalFrame("Criar Template");
            frame.setDefaultCloseOperation(JInternalFrame.DISPOSE_ON_CLOSE);
            frame.setMaximizable(true);
            frame.setClosable(true);
            PanelTemplate p = new PanelTemplate(sizeDialog.getSize());
            frame.setContentPane(p);
            frame.setBounds(0, 0, 800, 600);
            desktopPane.add(frame);
            frame.setVisible(true);
            setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
        }
    }

    private class DragDropFileListener implements DropTargetListener {

        @Override
        public void dragEnter(DropTargetDragEvent dtde) {
            panelMiniPhoto.removeAll();
        }

        @Override
        public void dragOver(DropTargetDragEvent dtde) {
            System.out.println("Over");
        }

        @Override
        public void dropActionChanged(DropTargetDragEvent dtde) {
            System.out.println("Changed");
        }

        @Override
        public void dragExit(DropTargetEvent dte) {
            System.out.println("Exit");
        }

        @Override
        public void drop(DropTargetDropEvent event) {
            System.out.println("Drop");
            // Accept copy drops
            event.acceptDrop(DnDConstants.ACTION_COPY);

            // Get the transfer which can provide the dropped item data
            Transferable transferable = event.getTransferable();

            // Get the data formats of the dropped item
            DataFlavor[] flavors = transferable.getTransferDataFlavors();

            // Loop through the flavors
            for (DataFlavor flavor : flavors) {
                try {
                    // If the drop items are files
                    if (flavor.isFlavorJavaFileListType()) {
                        // Get all of the dropped files
                        List files = (List) transferable.getTransferData(flavor);
                        // Loop them through
                        StringBuffer errors = new StringBuffer("Arquivos não suportados: ");
                        boolean hasErrors = false;
                        for (Object file : files) {
                            // Print out the file path
                            //jTextArea1.append("\n" + ((File) file).getPath());                               
                            try {
                                read(((File) file).toURI());
                            } catch (IOException exception) {
                                errors.append(((File) file).getPath());
                                hasErrors = true;
                            }
                        }
                        if (hasErrors) {
                            JOptionPane.showMessageDialog(null, errors.toString());
                        }
                    }
                } catch (Exception e) {
                    // Print out the error stack
                    e.printStackTrace();
                }
            }
            // Inform that the drop is complete
            event.dropComplete(true);
        }
    }

    private void createViewThumbnail(Figure figure) {
        DrawingView viewThumbnail = new DefaultDrawingView();
        viewThumbnail.setDrawing(createDrawing());
        ((AbstractFigure) figure).setBounds(new Rectangle2D.Double(0, 0, 100, 100));
        viewThumbnail.getDrawing().add(figure);
        ((JComponent) viewThumbnail).setMaximumSize(new Dimension(200, 100));
        editor.add(viewThumbnail);
        panelMiniPhoto.add((JComponent) viewThumbnail);
        panelMiniPhoto.add(javax.swing.Box.createRigidArea(new Dimension(0, 20)));
        repaint();
    }

    private void read(final URI f) throws IOException {
        // Create a new drawing object
        final Drawing newDrawing = createDrawing();
        if (newDrawing.getInputFormats().size() == 0) {
            throw new InternalError("Drawing object has no input formats.");
        }

        // Try out all input formats until we succeed
        IOException firstIOException = null;
        for (InputFormat format : newDrawing.getInputFormats()) {
            try {
                format.read(f, newDrawing);
                Runnable r = new Runnable() {
                    @Override
                    public void run() {
                        createViewThumbnail(newDrawing.getChild(0));
                    }
                };
                if (SwingUtilities.isEventDispatchThread()) {
                    r.run();
                } else {
                    try {
                        SwingUtilities.invokeAndWait(r);
                    } catch (InterruptedException ex) {
                        // suppress silently
                    } catch (InvocationTargetException ex) {
                        InternalError ie = new InternalError("Error setting drawing.");
                        ie.initCause(ex);
                        throw ie;
                    }
                }
                // We get here if reading was successful.
                // We can return since we are done.
                return;
                //
            } catch (IOException e) {
                // We get here if reading failed.
                // We only preserve the exception of the first input format,
                // because that's the one which is best suited for this drawing.
                if (firstIOException == null) {
                    firstIOException = e;
                }
            }
        }
        throw firstIOException;
    }
    
    private class InternalFramePanelRecordListener extends InternalFrameAdapter {
        private PanelRecord panelRecord1;

        public InternalFramePanelRecordListener(PanelRecord panelRecord1) {
            this.panelRecord1 = panelRecord1;
        }
            
        @Override
        public void internalFrameClosing(InternalFrameEvent e) {
            panelRecord1.removeTempFile();
        }   
    }
}